import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { getUserInfo } from "@/api/auth.js";
import { serialRequest } from "@/utils/requestUtils.js";

/**
 * 登录信息状态
 * @type {StoreDefinition<"login", {}, {}, {}>}
 */
export const useLoginStore = defineStore("login", () => {
  // token
  const token = ref(sessionStorage.getItem("token") || "");
  const setToken = (value) => {
    token.value = value;
    sessionStorage.setItem("token", value);
  };
  const getToken = () => {
    return token;
  };

  // 用户信息
  const userInfo = ref({});
  const userId = computed(() => {
    return userInfo.value?.userName;
  });

  let userLoading = serialRequest(getUserInfo);
  const checkingUserInfo = async ({ isForce, isSilent } = {}) => {
    if (token.value) {
      if (!userId.value || isForce) {
        let res = await userLoading({ xIsSilent: isSilent });
        userInfo.value = res.user || {};
      }
    }

    return userInfo;
  };

  // 有token先获取用户信息
  if (token.value) {
    checkingUserInfo({
      isSilent: true,
    });
  }

  const getTheUserInfo = (options) => {
    checkingUserInfo(options);
    return userInfo;
  };
  const getUserId = (options) => {
    checkingUserInfo(options);
    return userId;
  };

  // 登录标识
  const isLogined = computed(() => {
    return (
      !!token.value && userInfo.value && Object.keys(userInfo.value).length > 0
    );
  });

  const checkingLogined = async (config) => {
    await checkingUserInfo(config);
    return isLogined;
  };

  const getIsLogined = (config) => {
    checkingUserInfo(config);
    return isLogined;
  };

  const clear = () => {
    setToken("");
    userInfo.value = null;
  };

  const checkingAll = async (options) => {
    return Promise.all([checkingUserInfo(options)]);
  };

  return {
    setToken,
    getToken,
    checkingLogined,
    getIsLogined,

    checkingUserInfo,
    getUserInfo: getTheUserInfo,
    getUserId,

    checkingAll,
    clear,
  };
});
